package app.action;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import app.ui.MainFrame;
import app.ui.MakeDataFileUi;
import app.ui.StartUi;

public class StartAction implements ActionListener {
	private StartUi mPanel;
	private File file;
	// private CreateDataFileUi createDataFileUi;
	private MakeDataFileUi createDataFileUi;

	public StartAction(StartUi mPanel) {
		this.mPanel = mPanel;
	}

	public void actionPerformed(ActionEvent e) {
		Object obj = e.getSource();

		if (obj instanceof JButton) {
			JButton jButton = (JButton) obj;

			if (jButton == mPanel.getjButton1()) {
				showFileChooser();
			} else if (jButton == mPanel.getjButton2()) {
				if (createDataFileUi != null) {
					createDataFileUi.displayThis(true);
				} else {
					this.createDataFileUi = new MakeDataFileUi(mPanel.getmFrame());
					createDataFileUi.addThisToMainFrame();
				}
			} else if (jButton == mPanel.getjButton3()) {
				if (mPanel.getmFrame().getQuestionUI() != null) {
					mPanel.getmFrame().getQuestionUI().displayThis(true);
				}
			}
		}
	}

	private void showFileChooser() {
		String curDir = null;
		curDir = mPanel.getmFrame().getAppInit().getUtilities().getAppProp()
				.getProperty(MainFrame.LASTDIR);
		this.file = new File(curDir);

		JFileChooser jFileChooser = new JFileChooser(curDir);
		String[] acceptExtention = { "dat" };
		FileUtilities fileFilter = new FileUtilities(acceptExtention);

		jFileChooser.setFileFilter(fileFilter);
		jFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

		int returnVal = jFileChooser.showDialog(mPanel, "Open");

		if (returnVal == JFileChooser.APPROVE_OPTION) {
			this.file = jFileChooser.getSelectedFile();
			if (fileFilter.getExtension(file).equalsIgnoreCase(acceptExtention[0])) {
				mPanel.getmFrame().setTextSource(file);
				mPanel.getjButton3().setEnabled(true);
			} else {
				JOptionPane.showMessageDialog(mPanel, "File is not supported!");
			}
			jFileChooser = null;
		}
	}
}